package com.jbit.dm_160.controller;

import com.alipay.api.AlipayApiException;
import com.jbit.dm_160.alipay.entity.AlipayOrderInfo;
import com.jbit.dm_160.alipay.entity.AlipayTradeInfo;
import com.jbit.dm_160.model.dto.OrderInfoDTO;
import com.jbit.dm_160.model.entity.Order;
import com.jbit.dm_160.service.OrderService;
import com.jbit.dm_160.alipay.AliPayUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/alipay")
public class PayController {
    @Resource
    private OrderService orderService;
    @GetMapping("/pay/{orderNo}")
    public String payInfo(@PathVariable String orderNo){
        OrderInfoDTO order = orderService.getOrderInfoByOrderNo(orderNo);
        AlipayOrderInfo orderInfo = new AlipayOrderInfo();
        orderInfo.setOutTradeNo(order.getOrderNo());
        orderInfo.setSubject(order.getItemName());
        orderInfo.setTotalAmount(order.getTotalAmount());
        try {
            return AliPayUtil.pay(orderInfo);
        } catch (AlipayApiException e) {
            //支付失败时
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param request
     * @return
     */
    @GetMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request, AlipayTradeInfo tradeInfo){
        boolean flag = AliPayUtil.signature(request);
        if (flag){
//            tradeInfo.getTrade_no();//支付宝交易号;
//            tradeInfo.getOut_trade_no();
            Order order = new Order();
            order.setOrderNo(tradeInfo.getOut_trade_no());
            order.setAliTradeNo(tradeInfo.getTrade_no());
            Integer count = orderService.updateOrderByAlipay(order);
            return count==1 ? "交易成功" : "交易失败";
        }
        return null;
    }
}
